package uno.linze.interview_question.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import uno.linze.interview_question.domain.Question;
import uno.linze.interview_question.domain.QuestionTagRelation;
import uno.linze.interview_question.dto.PagedResponse;
import uno.linze.interview_question.dto.QuestionDTO;
import uno.linze.interview_question.dto.TagDTO;
import uno.linze.interview_question.service.QuestionService;
import uno.linze.interview_question.mapper.QuestionMapper;
import uno.linze.interview_question.mapper.QuestionTagRelationMapper;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
* @author wangy
* @description 针对表【question(面试问题/题目主表)】的数据库操作Service实现
* @createDate 2025-09-27 12:57:25
*/
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question>
    implements QuestionService{

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionTagRelationMapper questionTagRelationMapper;

    @Override
    public PagedResponse<QuestionDTO> queryQuestions(Integer page, Integer size, Integer categoryId, Integer difficulty, Integer tagId, String keyword) {
        // 参数验证和��认值处理
        if (page == null || page < 1) {
            page = 1;
        }
        if (size == null || size < 1) {
            size = 20;
        }

        // 计算偏移量
        Integer offset = (page - 1) * size;

        // 查题目列表
        List<QuestionDTO> questionList = questionMapper.selectQuestionsWithPagination(
                offset, size, categoryId, difficulty, tagId, keyword);

        // 查询总数
        Long total = questionMapper.countQuestionsWithConditions(
                categoryId, difficulty, tagId, keyword);

        // 构建分页响��
        return new PagedResponse<>(total, questionList);
    }

    @Override
    public QuestionDTO getQuestionById(Integer id) {
        return questionMapper.selectQuestionById(id);
    }

    @Override
    @Transactional
    public QuestionDTO createQuestion(QuestionDTO questionDTO) {
        // 参数验证
        if (questionDTO == null || questionDTO.getTitle() == null || questionDTO.getTitle().trim().isEmpty()) {
            throw new IllegalArgumentException("题目标题不能为空");
        }

        // 构建Question实体
        Question question = new Question();
        question.setOriginalId(questionDTO.getOriginalId());
        question.setTitle(questionDTO.getTitle());
        question.setDifficulty(questionDTO.getDifficulty());
        question.setViewNum(questionDTO.getViewNum() != null ? questionDTO.getViewNum() : 0);
        question.setCategoryId(questionDTO.getCategoryId());
        question.setAvgScore(questionDTO.getAvgScore() != null ?
            new BigDecimal(questionDTO.getAvgScore().toString()) : BigDecimal.ZERO);

        // 插入Question记录
        int insertResult = questionMapper.insertQuestion(question);
        if (insertResult <= 0) {
            throw new RuntimeException("创建题目失败");
        }

        // 获取生成的题目ID
        Integer questionId = question.getId();

        // 处理标签关联
        if (questionDTO.getTags() != null && !questionDTO.getTags().isEmpty()) {
            List<QuestionTagRelation> relations = new ArrayList<>();
            for (TagDTO tag : questionDTO.getTags()) {
                if (tag.getId() != null) {
                    QuestionTagRelation relation = new QuestionTagRelation();
                    relation.setQuestionId(questionId);
                    relation.setTagId(tag.getId());
                    relations.add(relation);
                }
            }

            if (!relations.isEmpty()) {
                int relationInsertResult = questionTagRelationMapper.batchInsertQuestionTagRelations(relations);
                if (relationInsertResult <= 0) {
                    throw new RuntimeException("创建题目标签关联失败");
                }
            }
        }

        // 查询并返回完整的QuestionDTO
        return questionMapper.selectQuestionById(questionId);
    }

    @Override
    @Transactional
    public QuestionDTO updateQuestion(Integer id, QuestionDTO questionDTO) {
        // 参数验证
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("题目ID不能为空");
        }
        if (questionDTO == null) {
            throw new IllegalArgumentException("题目信息不能为空");
        }

        // 检查题目是否存在
        QuestionDTO existingQuestion = questionMapper.selectQuestionById(id);
        if (existingQuestion == null) {
            throw new RuntimeException("题目不存在，ID: " + id);
        }

        // 构建Question实体
        Question question = new Question();
        question.setId(id);
        question.setOriginalId(questionDTO.getOriginalId());
        question.setTitle(questionDTO.getTitle());
        question.setDifficulty(questionDTO.getDifficulty());
        question.setViewNum(questionDTO.getViewNum());
        question.setCategoryId(questionDTO.getCategoryId());
        question.setAvgScore(questionDTO.getAvgScore() != null ?
            new BigDecimal(questionDTO.getAvgScore().toString()) : null);

        // 更新Question记录
        int updateResult = questionMapper.updateQuestionById(question);
        if (updateResult <= 0) {
            throw new RuntimeException("更新题目失败");
        }

        // 处理标签关联关系的更新
        // 先删除现有的标签关联关系
        questionTagRelationMapper.deleteByQuestionId(id);

        // 添加新的标签关联关系
        if (questionDTO.getTags() != null && !questionDTO.getTags().isEmpty()) {
            List<QuestionTagRelation> relations = new ArrayList<>();
            for (TagDTO tag : questionDTO.getTags()) {
                if (tag.getId() != null) {
                    QuestionTagRelation relation = new QuestionTagRelation();
                    relation.setQuestionId(id);
                    relation.setTagId(tag.getId());
                    relations.add(relation);
                }
            }

            if (!relations.isEmpty()) {
                int relationInsertResult = questionTagRelationMapper.batchInsertQuestionTagRelations(relations);
                if (relationInsertResult <= 0) {
                    throw new RuntimeException("更新题目标签关联失败");
                }
            }
        }

        // 查询并返回更新后的完整QuestionDTO
        return questionMapper.selectQuestionById(id);
    }
}
